package bll

import (
	"fmt"

	"7qule.com/sd3/CrossServer/src/common/onlinelog"
	"7qule.com/sd3/CrossServer/src/common/systemConstant"
	"public.com/goutil/syncUtil"
)

type gangTerritory struct {
	// 帮派领地
	data map[int32]int32

	// 数据同步对象
	dataLock *syncUtil.RWLocker
}

//
// GetData
// @Description: 获取帮派领地数据
// @receiver this
// @return map[int32]int32 帮派领地数据
//
func (this *gangTerritory) GetData() map[int32]int32 {
	if isOk, prevStack, currStack := this.dataLock.RLock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.RUnlock()

	return this.data
}

//
// AddPlayerCount
// @Description: 增加领地人数
// @receiver this
// @param layerId 层数id
//
func (this *gangTerritory) AddPlayerCount(layerId int32) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	_, ok := this.data[layerId]
	if !ok {
		this.data[layerId] = 1
		return
	}
	this.data[layerId] += 1
}

//
// ReducePlayerCount
// @Description: 减少领地人数
// @receiver this
// @param layerId 层数id
//
func (this *gangTerritory) ReducePlayerCount(layerId int32) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	this.data[layerId] -= 1
	if this.data[layerId] == 0 {
		this.DeleteGangTerritoryLayer(layerId)
	}
}

//
// DeleteGangTerritoryLayer
// @Description: 删除领地
// @receiver this
// @param layerId 层数id
//
func (this *gangTerritory) DeleteGangTerritoryLayer(layerId int32) {
	if isOk, prevStack, currStack := this.dataLock.Lock(systemConstant.DefaultLockTime); isOk == false {
		errMsg := fmt.Sprintf("Lock timeout! \n上一个堆栈:\n%s  \n当前堆栈:\n%s", prevStack, currStack)
		onlinelog.ErrorLog(errMsg)
		panic(errMsg)
	}
	defer this.dataLock.Unlock()

	delete(this.data, layerId)
}

//
// NewGangTerritoryLayer
// @Description: 新建GangTerritoryLayer对象
// @return *gangTerritory
//
func NewGangTerritory() *gangTerritory {
	return &gangTerritory{
		data:     make(map[int32]int32),
		dataLock: syncUtil.NewRWLocker(),
	}
}
